package top.fkxuexi.smartwork.tools;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.fkxuexi.smartwork.config.SmkConfig;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DbUtils {

    private static Logger log = LoggerFactory.getLogger(DbUtils.class);

    public static Connection getConn(SmkConfig config) {
        try{
            if (config.getUrl().toLowerCase().contains("mysql")) {
                Class.forName("com.mysql.jdbc.Driver");
            } else {
                log.error("暂时只支持MySQL 数据库，后续数据库的支持，请关注https://gitee.com/smartwork/smk-devtools");
                throw new RuntimeException("暂时只支持MySQL 数据库，后续数据库的支持，请关注https://gitee.com/smartwork/smk-devtools");
            }
            Connection conn = DriverManager.getConnection(config.getUrl(), config.getUser(), config.getPwd());
            return conn;
        }catch (Exception e1){
            e1.printStackTrace();
            throw new RuntimeException("数据库无法连接");
        }

    }

    public static void free(Connection connection) throws SQLException {
        if (connection != null) {
            connection.close();
        }
    }


    public static String getDbName(String url){
        if (url.toLowerCase().contains("mysql")){
            int index = url.indexOf("?");
            if (index == url.length()){
                return url.substring(url.lastIndexOf("/")+1,url.length());
            }else {
                return url.substring(url.lastIndexOf("/")+1,url.indexOf("?"));
            }
        }else if(url.toLowerCase().contains("oracle")){
            log.error("暂时只支持MySQL 数据库，后续数据库的支持，请关注https://gitee.com/smartwork/smk-devtools");
            throw new RuntimeException("暂不支持oracle数据库，后续的支持，请关注https://gitee.com/smartwork/smk-devtools");
        }
        throw new RuntimeException("暂不支持所给定的数据库，后续的支持，请关注https://gitee.com/smartwork/smk-devtools");
    }

}
